package com.shen.demo.demos.web.compont.aspect;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPatch;
import com.shen.demo.demos.web.compont.webSocket.HttpAuthHandler;
import com.shen.demo.demos.web.domain.entry.UserName;
import com.shen.demo.demos.web.service.UserNameService;
import com.shen.demo.demos.web.tool.JSONResult;
import com.shen.demo.demos.web.tool.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.Operation;
import org.springframework.stereotype.Component;

import java.util.List;

@Aspect
@Component
public class UserNameOperationAspect {
    @Autowired
    private UserNameService userService;

    @After("execution(* com.shen.demo.demos.web.mapper.UserNameMapper.update*(..))")
    public void afterUpdate(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof UserName) {
                UserName userName = (UserName) arg;
                // 在这里处理更新后的逻辑
                System.out.println("UserName updated: " + userName.getName());
                // 例如，你可以在这里调用服务方法，发送消息等
                // 查询所有 UserName 数据
                List<UserName> allUserNames = userService.list();

                // 将数据转换为 JSONObject 格式
                JSONObject jsonMessage = JSONResult.convertToJsonObject(allUserNames, OperationType.UPDATE.getOperationType());

                /*// 广播推送数据（区到点）
                HttpAuthHandler.broadcast(jsonMessage);*/

                /*// 定点推送数据（点到点）
                HttpAuthHandler.sendMessageToPage("Q01", jsonMessage);*/

                // 定点广播推送数据（特定区到点）
                HttpAuthHandler.broadcastToPage("Q01", jsonMessage);
            }
        }
    }

    @After("execution(* com.shen.demo.demos.web.mapper.UserNameMapper.insert*(..))")
    public void afterInsert(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof UserName) {
                UserName userName = (UserName) arg;
                // 在这里处理插入后的逻辑
                System.out.println("UserName inserted: " + userName.getName());
                // 例如，你可以在这里调用服务方法，发送消息等、

            }
        }
    }

    @After("execution(* com.shen.demo.demos.web.mapper.UserNameMapper.delete*(..))")
    public void afterDelete(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg instanceof UserName) {
                UserName userName = (UserName) arg;
                // 在这里处理删除后的逻辑
                System.out.println("UserName deleted: " + userName.getName());
                // 例如，你可以在这里调用服务方法，发送消息等
            }
        }
    }
}
